package com.sjy.common.utils;

import java.util.Date;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.JWTCreator.Builder;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.sjy.common.entity.SecuryUserDetail;
 
@Component
public class TokenUtil {
 
	@Value("${jwt.issuer}")
	private String ISSUER;//project-name
 
	@Value("${jwt.audience}")
	private String AUDIENCE;//web
 
	@Value("${jwt.expires_in}")
	private long EXPIRES_IN;//30
 
	private String encryKey = "project-name";
 
	private Algorithm ALGORITHM = Algorithm.HMAC256(encryKey);
 
	private Logger logger = LoggerFactory.getLogger(this.getClass());
 
	public static Boolean result = false;
	public static String message = "";
	
	public String generateTokenWithMap(Map<String,String> datas) {
		long currentTime = System.currentTimeMillis();
		Builder builder = JWT.create()
				 
				.withIssuer(ISSUER)
 
				.withIssuedAt(new Date(currentTime))// 签发时间
 
				.withExpiresAt(new Date(currentTime +  1000 *60* 60*24*60));
		if(datas!=null) {
			for(Map.Entry<String, String> data:datas.entrySet()) {
				builder.withClaim(data.getKey(), data.getValue());
			}
		}
		return builder.sign(ALGORITHM);
	}
	public String generateToken3Day(SecuryUserDetail user) {
		//String phone,String userName,String role,String channelId,String channelName
		EXPIRES_IN = 4320;
		
		long currentTime = System.currentTimeMillis();
		String token = JWT.create()
 
				.withIssuer(ISSUER)
 
				.withIssuedAt(new Date(currentTime))// 签发时间
 
				.withExpiresAt(new Date(currentTime + EXPIRES_IN * 1000 * 60))// 过期时间戳
				.withClaim("phonenumber", user.getPhonenumber())//自定义参数
				.withClaim("userType", user.getUserType())//自定义参数
				.withClaim("userId", user.getUserId())//自定义参数
				.withClaim("openId", user.getOpenId())//自定义参数
				.withClaim("userName", user.getUserName())//自定义参数
				.withClaim("loginName", user.getLoginName())//自定义参数
				
				.sign(ALGORITHM);
		return token;
	}
	public Map<String, Claim> parseTokenWithMap(String token) {
		if (null == token) {
			return null;
		}
		// Reusable verifier instance
		JWTVerifier verifier = JWT.require(ALGORITHM)

				.withIssuer(ISSUER)

				.build();
		DecodedJWT decodedJWT = verifier.verify(token);
		return decodedJWT.getClaims();
	}
 
	public String generateToken(String phonenumber,String userType,Long userId,String openId,String userName,String loginName) {
		long currentTime = System.currentTimeMillis();
		logger.info("=====generateToken===now    is " + new Date(currentTime));
		logger.info("=====generateToken===expire is " + new Date(currentTime + EXPIRES_IN * 1000 * 60));
 
		String token = JWT.create()
 
				.withIssuer(ISSUER)
 
				.withIssuedAt(new Date(currentTime))// 签发时间
 
				.withExpiresAt(new Date(currentTime + EXPIRES_IN * 1000 * 60))// 过期时间戳
				
				.withClaim("phonenumber", phonenumber)//自定义参数
				.withClaim("userType", userType)//自定义参数
				.withClaim("userId", userId)//自定义参数
				.withClaim("openId", openId)//自定义参数
				.withClaim("userName", userName)//自定义参数
				.withClaim("loginName", loginName)//自定义参数
				.sign(ALGORITHM);
		return token;
	}
	
	public SecuryUserDetail parseToken(String token) {
		if (null == token) {
			return null;
		}
		// Reusable verifier instance
		JWTVerifier verifier = JWT.require(ALGORITHM)

				.withIssuer(ISSUER)

				.build();
		DecodedJWT decodedJWT = verifier.verify(token);

		// verify issuer
		String issuer = decodedJWT.getIssuer();
		SecuryUserDetail securyUserDetail = new SecuryUserDetail();
		// verity 自定义参数

		securyUserDetail.setPhonenumber( decodedJWT.getClaim("phonenumber").asString());
		
		securyUserDetail.setUserType(decodedJWT.getClaim("userType").asString());
		securyUserDetail.setUserId(decodedJWT.getClaim("userId").asLong());
		securyUserDetail.setOpenId(decodedJWT.getClaim("openId").asString());
		securyUserDetail.setUserName(decodedJWT.getClaim("userName").asString());
		securyUserDetail.setLoginName(decodedJWT.getClaim("loginName").asString());
		return securyUserDetail;
	}
 
	public boolean verifyToken(String token) {
		try {
			if (null == token) {
				result = false;
				message = "token is null";
				return false;
			}
			// Reusable verifier instance
			JWTVerifier verifier = JWT.require(ALGORITHM)
 
					.withIssuer(ISSUER)
 
					.build();
			DecodedJWT decodedJWT = verifier.verify(token);
 
			// verify issuer
			String issuer = decodedJWT.getIssuer();
 
			// verity 自定义参数
			String phone = decodedJWT.getClaim("phone").asString();
			if (("").equals(phone)) {
				result = false;
				message = "user is error";
				return false;
			}
 
		} catch (TokenExpiredException e) {
			result = false;
			message = "token is expired";
			return false;
		}
		result = true;
		message = "token is verified";
		return true;
 
	}
 
}